import {ACCOUNTURL,ADVER,ADDADURL,ADVERNOPAGE} from '@/services/api'
import {ajax,ajaxnoparams,ajaxparems} from '@/services/ajaxrequest'
var options =[];
var data = new Object();
const datalist = [];
const accountlabel = [
    {
        title:'广告账号',
        value:'id',
        scopedSlots: { customRender: 'name' },
    }
];

const campaignlabel = [
    {
        title:'广告组',
        value:'id',
        slots: { title: 'customTitle' },
        scopedSlots: { customRender: 'name' },
    }
];
const selectedlabel = [
    {
        title:'已选',
        value:'id',
        index:'key',
        scopedSlots: { customRender: 'name' },
    }
];
var labelaccount = [
    {
        scopedSlots: { customRender: 'name' },
    }
];
var group = [];
export default {
    created(){
        this.spinning = true;
        this.listNew();
        this.updatename();
	},
	beforeCreate() {
        this.form = this.$form.createForm(this);
        this.formaddver = this.$form.createForm(this);
    },
    watch:{

    },
  data() {
    return {
        spinning:true,
        typeshow:0,
        options:options,
        primary:1,
        budgetmodes:'BUDGET_MODE_INFINITE',
        switchons:true,
        pagination: {
            onChange: page => {
                console.log("page", page);
            },
            pageSize: 10
        },
        datalist,
        datalists:[],
        account:[],
        accountlist:[],
        scene:0,
        pondtype:'a',
        pondtypenum:'1',
        onpond:'1',
        pondtypetrue:false,
        pondtrue:true,
        name:'',
        inputnum:1,
        picked: '',
        addtype:'a',
        checkedNames:'',
        tabnum:1,
        visible:false,
        launchacount:'',
        tabs:1,
        campaign_id:'',
        campaignlist:[],
        pages:false,
        accountlabel,
        campaignlabel,
        selectedlabel,
        advergroup:[],
        selectedgroup:[],
        adverlist:[],
        adverids:[],

        adverselectlist:[],
        acountcheck:[],
        campaigncheck:[],
        account_id:'',
        typename:'',
        checktrue:true,
        accounttype:'APP',
        group,
        labelaccount,
        account_n:0,
        adverbox:false,
        confirmLoading:false,
        tableloading:false,
        loadingone:false,
        loadingtwo:false,
        checklist:[],
    };
  },
  methods: {
    //单选
    onClickRow (record) {
        return {
            on: {
                click: () => {
                    let keys = [];
                    keys.push(record.account_id); 
                    console.log(keys);

                    this.selectedRowKeys = keys;
                }
            }
        }
    },
    callback(key) {
        var account_id = this.launchacount;
        //请求已有广告组
        var parems = {"filtering":[
            {"field":'landing_type',"operator":'EQUALS',"value":'APP'},
            {"field":'account_id',"operator":'EQUALS',"value":account_id}
        ]};
        ajaxparems(ADVER,parems).then((res) => {
            var result=res.data;
			this.datalist =result.data.list;
        })
        //请求条件已有广告组
        var videoparems = {"filtering":[
            {"field":'landing_type',"operator":'EQUALS',"value":'APP'},
            {"field":'account_id',"operator":'EQUALS',"value":account_id}
        ]};
        ajaxparems(ADVER,videoparems).then((res) => {
            var result=res.data;
			this.datalists =result.data.list;
        })
        this.tabs = key;
        this.onpond = key;
    },
    onradio(e){
        //选择单个广告组
        this.campaign_id = e.target.value;
    },
    oncampaign(e){
        if(this.campaignlist.indexOf(e.target.value) ==-1){
            this.campaignlist.push(e.target.value);
        }else{
            this.campaignlist.splice(this.campaignlist.indexOf(e.target.value),1);
        }
    },
    onSearch(value) {
        var parems = {"filtering":[{"field":'id',"operator":'EQUALS',"value":value},{"field":'name',"operator":'LIKE',"value":value}]};
        ajaxparems(ADVER,parems).then((res) => {
            var result=res.data;
			this.datalist =result.data.list;
		})
    },
    actives(e){
        var nowDate = new Date();
        let date = {
            month: nowDate.getMonth() + 1,
            date: nowDate.getDate(),
        }
        let hour = nowDate.getHours(); // 时
        let minute = nowDate.getMinutes(); // 分
        let second = nowDate.getSeconds(); // 秒
        var newname = '';
       if(e.target.value =="APP"){
            newname = "应用推广";
       }else if(e.target.value=="LINK"){
            newname = "销售线索收集";
       }
       this.name = newname+'_'+date.month+'_'+date.date+'_'+hour+':'+minute+':'+second;
    },
    activeson(e){
        var name = e.target.value;
        this.typename = name;
        var account_id = this.launchacount;
        //请求条件已有广告组
        var videoparems = {"filtering":[
            {"field":'landing_type',"operator":'EQUALS',"value":name},
            {"field":'account_id',"operator":'EQUALS',"value":account_id}
        ]};
        ajaxparems(ADVER,videoparems).then((res) => {
            var result=res.data;
			this.datalists =result.data.list;
		})
    },
    onactives(e,num){
        // console.log(e);
        this.scene =num;
    },
    onpondtype(e){
        //创意,定向创建
        if(e.target.value =='b'){
            this.pondtypenum = '1'
            this.onpond = '1';
            // console.log(this.pondtype);
            this.pondtypetrue = true;
            this.pondtrue = false;
            this.tabnum = 1;
        }else{
        
            this.pondtypetrue = false;
            this.pondtrue = true;
            this.inputnum =1;
        }
        // console.log(this.pondtype);
    },
    onaddtype(e){
        //自定义创建
        if(e.target.value =='b'){
            this.tableloading = true;
            ajax(ACCOUNTURL,"").then((res) => {
                var result=res.data;
                if(result.code =="SUCCESS"){
                    this.tableloading = false;
                    this.account =result.data;
                }else{
                    this.tableloading = false;
                    this.$message.Error(result.message, 3)
                }
            });
        }
        this.addtype = e.target.value;
    },
    onSearchaccount(v){
        var parems = {"filtering":[{"field":"name","operator":"LIKE","value":v}]};
        ajaxparems(ACCOUNTURL,parems).then((res) => {
            var result=res.data;
            console.log(result);
            if(result.code =="SUCCESS"){
                this.account =result.data;
            }else{
                this.$message.Error(result.message, 3)
            }
        });
    },
    budget(e){
        this.budgetmodes = e.target.value;
    },
    updatename(){
        //应用名称
        var nowDate = new Date();
        let date = {
            month: nowDate.getMonth() + 1,
            date: nowDate.getDate(),
        }
        let hour = nowDate.getHours(); // 时
        let minute = nowDate.getMinutes(); // 分
        let second = nowDate.getSeconds(); // 秒
        var newname = "应用推广";
        this.name = newname+'_'+date.month+'_'+date.date+'_'+hour+':'+minute+':'+second;
    },
    listNew(){
        //请求广告主账户列表
        ajax(ACCOUNTURL,"").then((res) => {
            var result=res.data;
            if(result.code =="SUCCESS"){
                this.options =result.data;
            }else{
                this.$message.Error(result.message, 3)
            }
        });

        this.spinning = false;
    },
    cancels(){
        this.$router.push('/promotion/advering/advers')
    },
    determines(){
        this.form.validateFieldsAndScroll((err, values) => {
            console.log(err);
            var types = this.typeshow;

            if(types =="0"){
                 this.$message.error("请选择推广目的", 3);
                 return;
            }else if(types =="1"){
                data.landing_type = "APP";
            }else if(types =="2"){
                data.landing_type = "LINK";
            }else if(types =="3"){
                data.landing_type = "AWEME";
            }
            
            var primary = this.primary;
            if(primary ==2){
                if(values.budget ==undefined){
                    this.$message.error("请输入预算值", 3);
                    return;
                }
                data.budget = values.budget;
                data.budget_mode = "BUDGET_MODE_DAY";
            }else{
                data.budget_mode = "BUDGET_MODE_INFINITE";
            }
            data.campaign_name = values.name;
            data.advertiser_id = this.form.getFieldValue('advertiser_id');
            var switchon = this.switchons;
            if(switchon ==true){
                data.operation = "disable";
            }else{
                data.operation ="enable";
            }
            var parems = data;
			ajaxnoparams("1657869217074189",ADDADURL,parems).then((res) => {
				var result=res.data;
				if(result.code =="SUCCESS"){
                    this.$message.success(result.message, 3).then(
                        this.$router.push('/promotion/advering/advers')
                    );
				}else{
 					this.$message.error(result.message, 3)
				}
			})
		});
    },
    onChange(checked) {
        this.switchons = checked;
    },
    onback(){
        // 批量取消创建
        this.visible = true;
    },
    handleCancel(){
        //取消创建弹窗(取消)
        this.visible = false;
    },
    handleOk(){
        //取消创建弹窗(确定)
        this.$router.go(-1);//返回上一层
            window.localStorage.removeItem("one");
            window.localStorage.removeItem("two");
            window.localStorage.removeItem("three");
        this.visible = false;
    },
    onaccount(e,n){
        this.loadingone = true;
        this.account_id = e;
        this.account_n = n;
        this.checktrue = false;

        // //点击账户名称获取广告组
        var accountparems = {"filtering":[
            {"field":'account_id',"operator":'EQUALS',"value":e},
            {"field":'landing_type',"operator":'EQUALS',"value":'APP'},
			{"field":"status","operator":"NOT_IN","value":["CAMPAIGN_STATUS_DELETE"]}
        ]};

        // console.log(this.adverlist);

        ajaxparems(ADVERNOPAGE, accountparems).then((res) => {
            var result = res.data;
            if (result.code == "SUCCESS") {
                // this.group[n].advergroup = result.data;
                this.advergroup = result.data;
                this.loadingone = false;
            } else {
                this.loadingone = false;
                this.$message.error(result.message, 3);
            }
        });
    },
    addadver(){
        //新增广告组
        this.adverbox = true;
    },
    adverCancel(){
        // 取消广告组创建
        this.adverbox = false;
    },
    adverok(){
        this.confirmLoading = true;
        var data = {};
        this.formaddver.validateFieldsAndScroll((err, values) => {
            if(!err){
            data.advertiser_id = values['account_id'];
            data.campaign_name = values['name'];
            data.budget_mode = values['budget_mode'];
            if(values['budget'] !=undefined){
                data.budget = values['budget'];
            }
            data.landing_type = values['landing_type'];
            var parems = data;
            // console.log(parems);
                ajaxnoparams(values['account_id'],ADDADURL,parems).then((res) => {
                    var result=res.data;
                    if(result.code =="SUCCESS"){
                        this.$message.success(result.message, 3).then(
                            this.adverbox = false
                        );
                        this.confirmLoading = false;
                    }else{
                        this.$message.error(result.message, 3)
                        this.confirmLoading = false;
                    }
                })
            }
            
        })
    },
    onSearchadver(v){
        //广告组按条件查询
        var accountparems = {"filtering":[
            {"field":'account_id',"operator":'EQUALS',"value":this.account_id},
            {"field":'landing_type',"operator":'EQUALS',"value":this.accounttype},
            {"field":'name',"operator":'LIKE',"value":v},
        ]};
        ajaxparems(ADVER, accountparems).then((res) => {
            var result = res.data;
            if (result.code == "SUCCESS") {
                this.advergroup = result.data.list;
            } else {
                this.$message.error(result.message, 3);
            }
        });

    },
    activesontype(e){

        //广告组按类型查询
       this.accounttype = e.target.value;
       this.group.forEach((res,index)=>{
            this.group[index].advergroup = [];
       });

       var accountparems = {"filtering":[
            {"field":'account_id',"operator":'EQUALS',"value":this.account_id},
            {"field":'landing_type',"operator":'EQUALS',"value":e.target.value},
        ]};
        ajaxparems(ADVER, accountparems).then((res) => {
            var result = res.data;
            if (result.code == "SUCCESS") {
                this.advergroup = result.data.list;
            } else {
                this.$message.error(result.message, 3);
            }
        });
       this.selectedgroup = [];
       this.adverlist =[];

    },
    onadver(e){
        this.loadingtwo = true;
        //点击选择广告组
        var n = this.account_n;
        var adver = e.target.value;

        if(this.adverlist.indexOf(adver) ===-1){
            this.adverlist.push(adver);
            this.adverids.push(adver.id);
            this.campaigncheck.push(adver);
            if(!this.group[n].advergroup){
                this.group[n] = Object.assign({},this.group[n], {advergroup:[]});
                this.group[n].advergroup.push(adver)
            }else{
                this.group[n].advergroup.push(adver)
            }
        }else{
            this.adverlist.splice(this.adverlist.indexOf(adver),1)
            this.adverids.splice(this.adverids.indexOf(adver.id),1)
            this.campaigncheck.splice(this.campaigncheck.indexOf(adver),1)
            this.group[n].advergroup.splice(this.group[n].advergroup.indexOf(adver),1);
            // this.adverids.push(adver.id);
        }
        this.loadingtwo = false;

        // console.log(this.adverlist);
    

        // var grouplist =[];
        // if(this.adverlist.length > 0){
        //     console.log(this.adverlist);
        //     var parems = {"filtering":[{"field":'id',"operator":'IN',"value":this.adverlist}]}
        //     ajaxparems(ADVER, parems).then((res) => {
        //         var result = res.data;
        //         if (result.code == "SUCCESS") {
        //             result.data.list.forEach((r) =>{
        //                 grouplist.push({
        //                     name:r.name,
        //                     account_id:r.account_id,
        //                     key:n,
        //                 });
        //             });
        //             this.selectedgroup = grouplist;
        //             this.loadingtwo = false;
        //         } else {
        //             this.loadingtwo = false;
        //             this.$message.error(result.message, 3);
        //         }
        //     });
        // }else{
        //     this.loadingtwo = false;
        //     this.selectedgroup = [];
        // }


        // if(this.adverlist.indexOf(e.target.value) ===-1){
        //     this.adverlist.push(e.target.value);
        //     this.campaigncheck.push(e.target.value);
        //     if(!this.group[n].advergroup){
        //         this.group[n] = Object.assign({},this.group[n], {advergroup:[]});
        //         this.group[n].advergroup.push(e.target.value)
        //     }else{
        //         this.group[n].advergroup.push(e.target.value)
        //     }
        // }else{
        //     this.adverlist.splice(this.adverlist.indexOf(e.target.value),1)
        //     this.campaigncheck.splice(this.campaigncheck.indexOf(e.target.value),1)
        //     this.group[n].advergroup.splice(this.group[n].advergroup.indexOf(e.target.value),1);
        // }

        // var grouplist =[];
        // if(this.adverlist.length > 0){
        //     console.log(this.adverlist);
        //     var parems = {"filtering":[{"field":'id',"operator":'IN',"value":this.adverlist}]}
        //     ajaxparems(ADVER, parems).then((res) => {
        //         var result = res.data;
        //         if (result.code == "SUCCESS") {
        //             result.data.list.forEach((r) =>{
        //                 grouplist.push({
        //                     name:r.name,
        //                     account_id:r.account_id,
        //                     key:n,
        //                 });
        //             });
        //             this.selectedgroup = grouplist;
        //             this.loadingtwo = false;
        //         } else {
        //             this.loadingtwo = false;
        //             this.$message.error(result.message, 3);
        //         }
        //     });
        // }else{
        //     this.loadingtwo = false;
        //     this.selectedgroup = [];
        // }
    },
    onclose(e,n){
        //点击关闭广告组
        this.adverlist.splice(this.adverlist.indexOf(e),1);



        this.adverids.splice(this.adverids.indexOf(e.id),1)

        this.group[n].advergroup.splice(this.group[n].advergroup.indexOf(e),1);

        // if(this.adverlist.length >0){
        //         var parems = {"filtering":[{"field":'id',"operator":'IN',"value":this.adverlist}]}
        //         ajaxparems(ADVER, parems).then((res) => {
        //             var result = res.data;
        //             if (result.code == "SUCCESS") {
        //                 this.selectedgroup = result.data.list;
        //             } else {
        //                 this.$message.error(result.message, 3);
        //             }
        //         });
        // }else{
        //         this.selectedgroup = [];
        // }
    },
    
    onnext(){
        this.logging = true;
        //下一步
        var storage=window.localStorage;
        if(storage.getItem("one") !=null){
            storage.removeItem("one");
            storage.removeItem("two");
            storage.removeItem("three");
        }
        this.form.validateFieldsAndScroll(async (err, values) => {
            var data = '';
            var val = {};
            var d = '';
            if(err){
                this.logging = false;
                return;
            }
            if(this.scene ==3){
            // 自定义创建
                if(this.addtype =='a'){
                    if(this.tabs ==1){
                        values['campaign_name'] = values['name'];
                        await ajaxnoparams(values['advertiser_id'],ADDADURL,values).then((res) => {
                            var result=res.data;
                            if(result.code =="SUCCESS"){
                                    values['type'] = 1;
                                    values['scene'] = this.scene;
                                    values['tabs'] = this.pondtype;
                                    values['campaignlist'] = result.data.campaign_id;
                                    data = values;
                                    d = JSON.stringify(data);
                                    storage.setItem("one",d);
                            }else{
                                this.logging = false;
                                this.$message.error(result.message, 3)
                            }
                        })
                    }else{
                        if(this.campaignlist.length <=0){
                            this.$message.error('请选择广告组');
                            this.logging = false;
                            return;
                        }
                        if(this.campaignlist.length >=50){
                            this.$message.error('超出选择数量,限制为50条',3);
                            this.logging = false;
                            return;
                        }
                        val["landing_type"] = values.landing_type;
                        val['advertiser_id'] = values.advertiser_id;
                        val['type'] =2;
                        val['campaignlist'] =  this.campaignlist;
                        val['tabs'] = this.pondtype;
                        val['scene'] = this.scene;
                        data = val;
                        d = JSON.stringify(data);
                        storage.setItem("one",d);
                    }
                }else{

                    if(this.group.length <=0){
                        this.$message.error('请选择广告投放账户');
                        return;
                    }
                    var list = [];
                    for(var i = 0;i <this.group.length;i++){
                        var obj = {};
                        if(!this.group[i].advergroup){
                            this.$message.error('每个广告账户至少选择一个广告组');
                            this.logging = false;
                            return;
                        }
                        obj.advertiser_id = this.group[i].account_id;
                        obj.campaignlist = this.group[i].advergroup
                        list.push(obj);
                    }
                    val['list'] = list;
                    val['tabs'] = this.pondtype;
                    val['scene'] = this.scene;
                    val['type'] = 3;
                    val['landing_type'] =values.landing_type;
                    // val['advertiser_id'] = advertiserlist;//广告主
                    // val['campaignlist'] = campaigncheck;//选中得广告组
                    data = val;
                    // console.log(data);
                    d = JSON.stringify(data);
                    storage.setItem("one",d);
                }
            }else{
                // 广告组创建
                if(this.tabs ==1){
                    values['campaign_name'] = values['name'];
                        //新增广告组
                        await ajaxnoparams(values['advertiser_id'],ADDADURL,values).then((res) => {
                            var result=res.data;
                            if(result.code =="SUCCESS"){
                                    values['type'] = 1;
                                    values['scene'] = this.scene;
                                    values['tabs'] = this.pondtype;
                                    values['campaignlist'] = result.data.campaign_id;
                                    data = values;
                            }else{
                                this.logging = false;
                                this.$message.error(result.message, 3)
                            }
                        })
                }else{
                    var campaign_id = this.campaign_id;
                    var parems = {"filtering":[{"field":'id',"operator":'EQUALS',"value":campaign_id}]}

                    await ajaxparems(ADVER,parems).then((res) => {
                        var result=res.data;
                        if(result.code =="SUCCESS"){
                            var info = result.data.list[0];
                            val['advertiser_id'] = values.advertiser_id;
                            if(info.budget_mode =="BUDGET_MODE_DAY"){
                                val.budget = info.budget;
                            }
                            val['landing_type'] = info.landing_type;
                            val['budget_mode'] = info.budget_mode;
                            val['num'] = 1;
                            val['name'] = info.name;
                            val['type'] = 1;
                            val['tabs'] = this.pondtype;
                            val['scene'] = this.scene;
                        }
                        data = val;
                    })
                }
                // 写进缓存
                d = JSON.stringify(data);
                storage.setItem("one",d);
            }
            this.logging = false;
            // console.log(storage.getItem('one'));
            // //跳转批量广告计划
            this.$router.push('/promotion/plan');
        })
    },
    
    handleChange(value){
        //广告投放账号是否选择
        //请求已有广告组
        var parems = {"filtering":[
            {"field":'landing_type',"operator":'EQUALS',"value":'APP'},
            {"field":'account_id',"operator":'EQUALS',"value":value}
        ]};
        ajaxparems(ADVER,parems).then((res) => {
            var result=res.data;
			this.datalist =result.data.list;
        })

        //请求条件已有广告组
        var videoparems = {"filtering":[
            {"field":'landing_type',"operator":'EQUALS',"value":'APP'},
            {"field":'account_id',"operator":'EQUALS',"value":value}
        ]};
        ajaxparems(ADVER,videoparems).then((res) => {
            var result=res.data;
			this.datalists =result.data.list;
        })
       this.launchacount = value;
    },
    customRow(record,index){
        //账号行点击
        return {
            on: {
              click: (e) => {

                console.log(e);

                console.log(record, index)

                console.log(record,index);
                // this.selectedRowKeys = [index]
                // this.selectedRows = [record]
              }
            }
        }

    },
    imgurl (name){
      return require('@/assets/img/'+name);
    }
  },
  computed: {
    rowSelection(){
        return {
            columnTitle:' ',
            hideDefaultSelections:true,
            onChange: (selectedRowKeys, selectedRows) => {
                selectedRows.forEach((item,index) =>{
                    selectedRows[index] = Object.assign({},selectedRows[index], {selectedgroup:[]});
                })
                this.group = selectedRows;

                // if(this.group.length >0){
                //     // 倒序拿最新
                //     var arr = selectedRows.reverse();
                //     this.group.push(arr[0]);
                // }else{

                //     this.group = selectedRows;
                // }
            },
        };
    },
  }
};